<!-- 封装柱状图，适用于单柱状图/多柱状图/折柱混合图 -->
<template>
  <div :style="{ height: height, width: width }"  :id="'canvas-box'+number">
  </div>
</template>

<script lang="ts" name="basicEchartsBar" setup>
import {
  ref,
  shallowRef,
  watch,
  nextTick,
  onMounted,
  onBeforeUnmount,
  getCurrentInstance,
  reactive
} from 'vue'
import { debounce } from 'lodash'

const { proxy } = getCurrentInstance() as any //类型可以为任意类型

// 入参
const props = defineProps({
  options: {
    type: Object,
    default: () => {
      return {}
    }
  },
  // 是否不跟之前的传入值合并
  notMerge: {
    type: Boolean,
    default: true
  },
  width: {
    type: String,
    default: "100%",
  },
  height: {
    type: String,
    default: "100%",
  },
  chartData: {
    type: Object,
    default: () => {
      return {
        name: [],
      }
    },
    required: true, //传入的报表数据
  },
  fontColor: {
    type: String,
    default: "",
  },
  showDataZoom: {
    type: Boolean,
    default: false,
  },
})
// 传给父元素，报表点击事件
const emits = defineEmits(['chart-click'])

// 报表信息
const eCharts = proxy.$ECharts
let chart = shallowRef<any>();
let colors = reactive([
  "rgba(177, 248, 252, 1)",
  "rgba(212, 195, 12, 1)",
  "rgba(91, 205, 96, 1)",
]); // 柱子颜色
let colorsChangeFrom = reactive([
  "rgba(241, 196, 15, 1)",
  "rgba(212, 195, 12, .3)",
  "rgba(91, 205, 96, .3)"
]); // 柱子渐变颜色

let colorsChangeTo = reactive([
  "rgba(2, 12, 20, 0.13)",
  "rgba(212, 195, 12, .01)",
  "rgba(91, 205, 96, .01)"
]); // 柱子渐变颜色
let number = ref(Math.random() + 1); // 报表id

watch(
    () => props.chartData,
    async () => {
      await nextTick()
      initChart()
    },
    {
      deep: true
    }
)

const resizeHandler = () => {
  chart.value.resize()
}
// 报表尺寸适配
const resizeHandlerOrigin = debounce(resizeHandler, 500)

// 初始化报表
const initChart = () =>{
  chart.value = eCharts.getInstanceByDom(document.getElementById(`canvas-box${number.value}`))
  if (chart.value === undefined) {
    chart.value = eCharts.init(document.getElementById(`canvas-box${number.value}`));
  }
  chart.value.clear();
  setOptions(props.chartData);
}

// 图表配置项
const setOptions = (chartData: any) => {
  if(!chartData.data) return
  const name = chartData.name;
  const label = chartData.label;
  let series: any[] = [];
  let yAxis: any[] = []
  let arr = Object.keys(chartData.data);

  arr.forEach((v, index) => {
    const item = chartData.data[v]
    let symbolData: any[] = []
    series.push({
      name: name[index],
      type: item.type,
      showSymbol: false, // 在 tooltip hover 的时候显示
      smooth: chartData.smoothLine ?? true,
      showBackground: true,
      barMaxWidth: chartData.barMaxWidth ? chartData.barMaxWidth : 16,
      stack: chartData?.stack ? 'item' : '',
      // 折线图内部区域的颜色
      areaStyle: {
        color: new eCharts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: item.colors[0] },
          { offset: 1, color: item.colors[1] },
        ]),
      },
      lineStyle: {
        color: item.lineColor ?? colors[index], // 折线颜色
      },
      label: {
        show: false
      }, // 柱子上方的数值
      itemStyle: {
        color: new eCharts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: item.colors[0] },
          { offset: 1, color: item.colors[1] },
        ]),
        label: {
          show: false, //开启显示
          position: 'top', //在上方显示
          textStyle: { //数值样式
            color: '#aaa',
            fontSize: 14
          }
        }
      },
      data: chartData.data[v].data,
      markPoint: {
        data: symbolData,
      },
      yAxisIndex: !!chartData?.yAxisIndexFlag ? index : 0
    });
    yAxis.push(
        {
          type: chartData.xAxisTYpe ? 'category' : chartData.xAxisTYpe,
          name: chartData.yAxisNameFlag ? chartData.yName[index] : '', // Y轴显示 单位
          inverse: !!chartData.xAxisTYpe,
          min: chartData.yAxisMinData,
          nameTextStyle: {
            color: "#fff",
            padding:[0,0,0,-10],
            fontSize: 16 // 设置y轴名称的字体大小
          },
          axisLabel: {
            show: true,
              color: props.fontColor ? props.fontColor : "rgba(222, 235, 255, 1)",
              fontSize: 14,
              fontFamily: "SourceHanSans"
          },
          axisLine: {
            show: false,//y轴线的颜色以及宽度
            lineStyle: {
              color: props.fontColor ? props.fontColor : "rgba(105, 215, 254, 1)",
            },
          },
          splitLine: {
            show: true,
            lineStyle: {
              color: props.fontColor ? props.fontColor : "rgba(105, 215, 254, .13)",
            },
          },
          data: chartData.xAxisTYpe ? label :  '',
        }
    )
  });

  // 设置默认的报表格式
  let defaultOptions = {
    // 图例位置
    grid: {
      left: '2%',
      right: '2%',
      bottom: props.showDataZoom ? '10%': '4%',
      top: '14%',
      containLabel: true
    },
    legend:{
      top: 0,
      itemWidth: 17,
      itemHeight: 8,
      textStyle:{
        fontSize:14,
        color: 'rgba(234, 235, 236, 1)'
      }
    },
    //  此处判断是否使用自定义 浮框
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
        label:{
          show:false,
        },
        crossStyle: {
          color: '#999'
        },
        shadowStyle: {
          color: "rgba(22, 93, 255, 0.1)", // 阴影颜色，可以是任意CSS颜色值
        }
      }
    },
    dataZoom: [
      {
        show: props.showDataZoom,
        type: 'slider',
        xAxisIndex: 0, //设置控制xAxis
        startValue: 0, // 从头开始。
        endValue: props.showDataZoom ? 5 : 12, // 默认展示7个
        height: 10,
        bottom: 5,
        zoomLock: true,
        brushSelect: false, // 刷选功能，设为false可以防止拖动条长度改变
      },
    ],
    xAxis: {
      type: chartData.xAxisTYpe ? chartData.xAxisTYpe : 'category',
      boundaryGap: true, // 显示间距设置为false
      axisLine: {
        show: !chartData.xAxisTYpe, //隐藏X轴轴线
        lineStyle: {
          color: "rgba(255, 255, 255, .1)",
        },
      },
      splitLine: {
        lineStyle: {
          color: "rgba(255,255,255,0.1)",
          type: "line",
        },
      },
      axisTick: {
        show: false, //隐藏X轴刻度
        alignWithLabel: true
      },
      axisLabel: {
        show: true,
          color: props.fontColor ? props.fontColor : "rgba(234, 235, 236, 1)",
          fontSize: 14,
          fontFamily: "SourceHanSansCN-Regular"
      },
      data: label,
    },
    yAxis: yAxis,
    series: series,
  };

  let options = {}

  if (isEmptyObj(props.options)) {
    options = defaultOptions
  } else {
    options = props.options
  }

  chart.value.setOption(options);
  window.addEventListener('resize', resizeHandlerOrigin)
}

// 判断传入的图表options是否为空
const isEmptyObj = (obj: object) => {
  return typeof obj === 'object' && JSON.stringify(obj) === '{}'
}

const initChartEvent = () => {
  cancelClickEvent()
  chart.value.on('click', (params?: any) => {
    emits('chart-click', params)
  })
}

// 取消点击事件
const cancelClickEvent = () => {
  chart.value.off('click')
}

onMounted(async () => {
  // 初始化报表
  await nextTick()
  initChart();
})
// 页面销毁操作
onBeforeUnmount(()=>{
  cancelClickEvent()
  window.removeEventListener('resize', resizeHandlerOrigin)
  // 页面销毁时 销毁图表
  if (!chart) {
    return;
  }
  chart.value.dispose();
  chart.value = null;
})
</script>

<style scoped>

</style>